package com.ruoyi.web.controller.biz;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.biz.domain.EquipmentInfo;
import com.ruoyi.biz.domain.MaintainManage;
import com.ruoyi.biz.service.IEquipmentInfoService;
import com.ruoyi.biz.service.IMaintainManageService;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.*;
import com.ruoyi.web.core.utils.SendMsgUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2020-11-30
 */
@RestController
@RequestMapping("/system/maintain/manage")
public class MaintainManageController extends BaseController
{
    @Autowired
    private IMaintainManageService maintainManageService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IEquipmentInfoService equipmentInfoService;
    @Resource
    private ISysDictDataService sysDictDataService;
    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:list')")
    @GetMapping("/list")
    @ApiOperation("查询保养管理列表")
    public TableDataInfo list(MaintainManage maintainManage)
    {
        startPage();
        logger.debug("进入查询保养列表");
        List<MaintainManage> list = maintainManageService.selectMaintainManageList(maintainManage);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    @ApiOperation("导出保养管理信息")
    public AjaxResult export(MaintainManage maintainManage)
    {
        List<MaintainManage> list = maintainManageService.selectMaintainManageList(maintainManage);
        ExcelUtil<MaintainManage> util = new ExcelUtil<MaintainManage>(MaintainManage.class);
        return util.exportExcel(list, "manage");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:query')")
    @GetMapping(value = "/{maintainId}")
    @ApiOperation("获取保养管理详情")
    public AjaxResult getInfo(@PathVariable("maintainId") Long maintainId)
    {
        return AjaxResult.success(maintainManageService.selectMaintainManageById(maintainId));
    }

    @PostMapping("/notice")
    public AjaxResult notice(@RequestBody MaintainManage maintainManage){
        //TODO 通知
        Map<String,Object> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("Start_Time",simpleDateFormat.format(maintainManage.getPlanBeginTime()));
        map.put("End_Time",simpleDateFormat.format(maintainManage.getPlanEndTime()));
        map.put("Equipment",maintainManage.getEquipmentName());
        map.put("Parts",maintainManage.getPosition());
        map.put("Type",maintainManage.getMaintainTypeName());
        map.put("Content",maintainManage.getContent());
        SysUser sysUser = sysUserService.getSysUserInfoByUserName(maintainManage.getAlarmContact());

        boolean flag = SendMsgUtil.sendMaintain(map, sysUser.getPhonenumber());
        if (flag){
            return AjaxResult.success("通知成功");
        }else {
            throw  new RuntimeException("通知失败，请联系管理员");
        }
    }

    /**
     * 新增【请填写功能名称】
     * 保养对象:MaintainManage(maintainId=null, maintainTypeId=2, code=JOasiuqw717, sort=null,
     * planBeginTime=Tue Aug 10 11:22:20 CST 2021, planEndTime=Sat Aug 28 00:00:00 CST 2021, status=0,
     * noticeStatus=41, equipmentId=5, alarmContact=admin, alarmContactName=null, deptId=null, currentUser=null,
     * dictLabel=null, equipmentName=null, position=手柄, content=手柄清洗, maintainTypeName=null, dictStatus=null)
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增保养管理")
    public AjaxResult add(@RequestBody MaintainManage maintainManage)
    {
        List<MaintainManage> maintainManages = maintainManageService.selectAll().stream().filter(item -> item.getPlanEndTime().before(new Date())).collect(Collectors.toList());;
        maintainManages.forEach(item->{
            if (item.getStatus()!=44){
                item.setStatus(44);
                maintainManageService.updateMaintainManage(item);
            }
        });

        logger.debug("保养对象:{}",maintainManage);
        //TODO 通知
        Map<String,Object> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("Start_Time",simpleDateFormat.format(maintainManage.getPlanBeginTime()));
        map.put("End_Time",simpleDateFormat.format(maintainManage.getPlanEndTime()));
        EquipmentInfo equipmentInfo = equipmentInfoService.selectEquipmentInfoById(maintainManage.getEquipmentId());
        SysDictData sysDictData = sysDictDataService.selectDictDataByMaintainManage(maintainManage.getMaintainTypeId());
        map.put("Equipment",equipmentInfo.getEquipmentName());
        map.put("Parts",maintainManage.getPosition());
        map.put("Type",sysDictData.getDictLabel());
        map.put("Content",maintainManage.getContent());
        SysUser sysUser = sysUserService.getSysUserInfoByUserName(maintainManage.getAlarmContact());
        SendMsgUtil.sendMaintain(map,sysUser.getPhonenumber());


        return toAjax(maintainManageService.insertMaintainManage(maintainManage));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改保养管理信息")
    public AjaxResult edit(@RequestBody MaintainManage maintainManage)
    {
        logger.debug("传递过来的信息:{}",maintainManage);
        return toAjax(maintainManageService.updateMaintainManage(maintainManage));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{maintainIds}")
    @ApiOperation("删除保养管理信息")
    public AjaxResult remove(@PathVariable Long[] maintainIds)
    {
        return toAjax(maintainManageService.deleteMaintainManageByIds(maintainIds));
    }

    @PreAuthorize("@ss.hasPermi('operate:maintain:manage:list')")
    @GetMapping("/getAllMaintainType")
    @ApiOperation("获取所有保养类别信息")
    public AjaxResult getAllMaintainType() {
        return AjaxResult.success(maintainManageService.getAllMaintainType());
    }

}
